#pragma once

#include<iostream>
#include <memory>
#include<functional>
#include<unordered_map>
#include<string>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Socket.hpp"
#include"TcpServer.hpp"
#include"HttpProtocol.hpp"
using namespace TcpServerModule;


using http_handler_t = std::function<void (HttpRequest&,HttpResponse&)>;
class HttpServer
{
public:
    HttpServer(int port)
    :_tsvr(std::make_unique<TcpServer>(port))
    {}
    //使http服务器运行起来
    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd,InetAddr cilent){
            return this->HandlerHttpRequest(sockfd, cilent);
        });
        _tsvr->Loop();
    }
    
    //url安全检查
    bool SafeCheck(const std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }

    //注册选择功能
    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }
    //处理http请求
    bool HandlerHttpRequest(SockPtr sockfd,InetAddr cilent)
    {
        LOG(LogLevel::DEBUG) << "HttpServer:get a new cilent" << sockfd->Fd() << "addr info:" << cilent.Addr();

        //将收到的请求存到http_request中
        std::string http_request;
        sockfd->Recv(&http_request);
        // std::cout << http_request;
        
        //构建request进行反序列化
        HttpRequest req;
        req.Deserialize(http_request);
        std::cout << "用户想要：" << req.Uri() << std::endl;
        //req.Print();
        //获取请求的文件
        // req.GetContent(req.Uri());

        HttpResponse resp;
        //请求分为两类：1.请求一般的静态资源 2.提交参数，写到正文body部分，进行交互
        if(req.IsHasArgs())
        {
            //2.提交参数，写到正文body部分，进行交互
            std::string service = req.Path();
            if(SafeCheck(service))
                _route[req.Path()](req,resp);//login
            else
                resp.Build(req);//debug,url error
        }
        else 
        {
            resp.Build(req);
        }

        //序列化
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);

        return true;
        // //读取请求，处理请求
        // //1.读取完整性--暂不做
        // //2.response序列request反序列

        // //报头
        //  std::string status_line = "HTTP/1.1 200 OK" + Sep + BlankLine;
        // //正文： 直接返回一个html网页
        // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                    <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title> Hello World</title>\
        //                    </head>\
        //                    <body>\
        //                    <p> Hello World</ p>\
        //                    </body> </html>";
        
        // std::string httpresponse = status_line + body;
        // sockfd->Send(httpresponse);
    }
    ~HttpServer()
    {}
private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route; //进行功能路由
};